package cn.work.Filter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import cn.work.util.DataBaseutil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalTime;


@WebFilter("/*")
public class AppointmentFilter implements javax.servlet.Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 过滤器初始化时无需手动获取数据库连接，已在方法中直接使用
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        LocalDateTime currentTime = LocalDateTime.now();
        String query = "SELECT id, service_period, service_date, state FROM appointment WHERE state != '已过期' AND state != '已完成'";
        try (Connection connection = DataBaseutil.getConnection();
             PreparedStatement stmt = connection.prepareStatement(query);
             ResultSet rs = stmt.executeQuery()) {

            while (rs.next()) {
                int id = rs.getInt("id");
                String servicePeriod = rs.getString("service_period");
                LocalDate serviceDate = rs.getDate("service_date").toLocalDate();
                String[] times = servicePeriod.split("-");
                String endTimeStr = times[0];
                LocalTime endTime = LocalTime.parse(endTimeStr);
                LocalDateTime appointmentEndTime = LocalDateTime.of(serviceDate, endTime);

                if (currentTime.isAfter(appointmentEndTime)) {
                    String updateQuery = "UPDATE appointment SET state = '已过期' WHERE id = ?";
                    try (PreparedStatement updateStmt = connection.prepareStatement(updateQuery)) {
                        updateStmt.setInt(1, id);
                        updateStmt.executeUpdate();
                    }
                }
            }
        } catch (SQLException e) {
            throw new ServletException("Database query error", e);
        }

        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 过滤器销毁时无需手动关闭连接
    }
}
